package cn.gong.movie.ui;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import cn.gong.movie.bean.Drama;
import cn.gong.movie.data.DataDrama;
import cn.gong.movie.enums.DbTaskType;
import cn.gong.movie.utils.DateUtils1;
import framework.annotation.ClickMethod;
import framework.annotation.InjectView;
import framework.base.BaseAct;
import framework.base.BaseAdap;
import framework.config.RequestCode;
import framework.config.Strings;
import framework.jiekou.MoreView;
import framework.utils.CollectionUtils;

public class ActDrama extends BaseAct {

	@InjectView(R.id.drama_lv_follow)
	private ListView followLv;
	@InjectView(R.id.drama_lv_want)
	private ListView wantLv;
	@InjectView(R.id.drama_lv_seen)
	private ListView seenLv;

	private ArrayList<Button> topButtons;
	private ArrayList<ListView> listViews;

	private int status = 0;

	private DramaAdap followAdap;
	private DramaWantAdap wantAdap;
	private DramaSeenAdap seenAdap;

	private boolean followHasMore;
	private boolean wantHasMore;
	private boolean seenHasMore;

	private ArrayList<Drama> followDramas;
	private ArrayList<Drama> wantDramas;
	private ArrayList<Drama> seenDramas;

	// private int followPage = 0;
	private long followWatchTime = -1;
	// private int wantPage = 0;
	private long wantLastIndex = -1;
	// private int seenPage = 0;
	private long seenLashIndex = -1;
	private Drama oprateFollowDrama;
	private Drama oprateWantDrama;
	private Drama oprateSeenDrama;

	@Override
	public void onCreateAct(Bundle savedInstanceState) {
		super.onCreateAct(savedInstanceState);
		setContentView(R.layout.drama);
		initTitle();

		topButtons = new ArrayList<Button>();

		topButtons.add(findButtonById(R.id.drama_bt_follow));
		topButtons.add(findButtonById(R.id.drama_bt_want));
		topButtons.add(findButtonById(R.id.drama_bt_seen));

		listViews = new ArrayList<ListView>();
		listViews.add(followLv);
		listViews.add(wantLv);
		listViews.add(seenLv);

		initFollowLv();
		initWantLv();
		initSeenLv();

		DataDrama.getFollowDramas(getContext(), followWatchTime, getDBCallBack());

	}

	@Override
	public void onDbCallBack(int dbTaskType, Object data) {
		super.onDbCallBack(dbTaskType, data);
		switch (DbTaskType.values()[dbTaskType]) {
		case dbTsGetFollowDramas:
			dbTsGetFollowDramas(data);
			break;
		case dbTsGetMoreFollowDramas:
			dbTsGetMoreFollowDramas(data);
			break;
		case dbTsGetWantDramas:
			dbTsGetWantDramas(data);
			break;
		case dbTsGetMoreWantDramas:
			dbTsGetMoreWantDramas(data);
			break;
		case dbTsGetSeenDramas:
			dbTsGetSeenDramas(data);
			break;
		case dbTsGetMoreSeenDramas:
			dbTsGetMoreSeenDramas(data);
			break;
		}
	}

	private void dbTsGetMoreSeenDramas(Object data) {
		ArrayList<Drama> moreDrama = (ArrayList<Drama>) data;
		seenDramas.addAll(moreDrama);
		seenHasMore = CollectionUtils.isNotBlank(moreDrama);
		if (seenHasMore) {
			seenLashIndex = moreDrama.get(moreDrama.size() - 1).getId();
		}
		seenAdap.notifyDataSetChanged();
	}

	private void dbTsGetSeenDramas(Object data) {
		seenDramas = (ArrayList<Drama>) data;
		seenHasMore = CollectionUtils.isNotBlank(seenDramas);
		if (seenHasMore) {
			seenLashIndex = seenDramas.get(seenDramas.size() - 1).getId();
		}
		seenAdap.notifyDataSetChanged();
	}

	private void dbTsGetMoreWantDramas(Object data) {
		ArrayList<Drama> moreDrama = (ArrayList<Drama>) data;
		wantHasMore = CollectionUtils.isNotBlank(moreDrama);
		if (wantHasMore) {
			wantLastIndex = moreDrama.get(moreDrama.size() - 1).getId();
		}
		wantDramas.addAll(moreDrama);
		wantAdap.notifyDataSetChanged();
	}

	private void dbTsGetWantDramas(Object data) {
		wantDramas = (ArrayList<Drama>) data;
		wantHasMore = CollectionUtils.isNotBlank(wantDramas);
		if (wantHasMore) {
			wantLastIndex = wantDramas.get(wantDramas.size() - 1).getId();
		}

		wantAdap.notifyDataSetChanged();
	}

	private void dbTsGetMoreFollowDramas(Object data) {
		ArrayList<Drama> moreDrama = (ArrayList<Drama>) data;
		followDramas.addAll(moreDrama);
		followHasMore = CollectionUtils.isNotBlank(moreDrama);
		if (followHasMore) {
			followWatchTime = moreDrama.get(moreDrama.size() - 1).getWatchTime();
		}
		followAdap.notifyDataSetChanged();
	}

	private void dbTsGetFollowDramas(Object data) {
		followDramas = (ArrayList<Drama>) data;

		followHasMore = CollectionUtils.isNotBlank(followDramas);
		if (followHasMore) {
			followWatchTime = followDramas.get(followDramas.size() - 1).getWatchTime();
		}
		followAdap.notifyDataSetChanged();
	}

	private void initTitle() {
		TextView titleTv = findTextViewById(R.id.title_bar_tv_title);
		setText(titleTv, "电视剧");
		viewGone(R.id.title_bar_ib_left);
	}

	private void initFollowLv() {
		followAdap = new DramaAdap(new MoreView() {

			@Override
			public View moreView() {
				View inflate = inflate(R.layout.more_item);
				TextView moreTv = findTextViewById(R.id.more_item_tv, inflate);
				if (followHasMore) {
					setText(moreTv, "更多");
				} else {
					setText(moreTv, "没有更多影片了");
				}
				return inflate;
			}
		});
		followLv.setAdapter(followAdap);
		followLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				oprateFollowDrama = (Drama) followAdap.getItem(position);
				if (oprateFollowDrama == null) {
					// more
					if (followHasMore) {
						DataDrama.getMoreFollowDramas(getContext(), followWatchTime, getDBCallBack());
					}
				} else {
					Intent intent = new Intent(getContext(), ActFollowDramaInfo.class);
					intent.putExtra(Strings.INTENT_EXTRA_DRAMA, oprateFollowDrama);
					openActForResult(intent, RequestCode.FOLLOW_DRAMA_INFO);
				}
			}
		});
	}

	private void initWantLv() {
		wantAdap = new DramaWantAdap(new MoreView() {

			@Override
			public View moreView() {
				View inflate = inflate(R.layout.more_item);
				TextView moreTv = findTextViewById(R.id.more_item_tv, inflate);
				if (wantHasMore) {
					setText(moreTv, "更多");
				} else {
					setText(moreTv, "没有更多影片了");
				}
				return inflate;
			}
		});
		wantLv.setAdapter(wantAdap);
		wantLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				oprateWantDrama = (Drama) wantAdap.getItem(position);
				if (oprateWantDrama == null) {
					// more
					if (wantHasMore) {
						DataDrama.getMoreWantDramas(getContext(), wantLastIndex, getDBCallBack());
					}
				} else {
					Intent intent = new Intent(getContext(), ActWantDramaInfo.class);
					intent.putExtra(Strings.INTENT_EXTRA_DRAMA, oprateWantDrama);
					openActForResult(intent, RequestCode.WANT_DRAMA_INFO);
				}
			}
		});
	}

	private void initSeenLv() {
		seenAdap = new DramaSeenAdap(new MoreView() {

			@Override
			public View moreView() {
				View inflate = inflate(R.layout.more_item);
				TextView moreTv = findTextViewById(R.id.more_item_tv, inflate);
				if (seenHasMore) {
					setText(moreTv, "更多");
				} else {
					setText(moreTv, "没有更多影片了");
				}
				return inflate;
			}
		});
		seenLv.setAdapter(seenAdap);
		seenLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				oprateSeenDrama = (Drama) seenAdap.getItem(position);
				if (oprateSeenDrama == null) {
					// more
					if (seenHasMore) {
						DataDrama.getMoreSeenDramas(getContext(), seenLashIndex, getDBCallBack());
					}
				} else {
					Intent intent = new Intent(getContext(), ActSeenDramaInfo.class);
					intent.putExtra(Strings.INTENT_EXTRA_DRAMA, oprateSeenDrama);
					openActForResult(intent, RequestCode.SEEN_DRAMA_INFO);
				}
			}
		});
	}

	@ClickMethod(R.id.title_bar_ib_right)
	protected void clickClose(View view) {
		closeAct();
		animScaleClose();
	}

	@ClickMethod(R.id.drama_bt_follow)
	protected void clickFollow(View view) {
		status = 0;
		statusChanage();
	}

	@ClickMethod(R.id.drama_bt_want)
	protected void clickWant(View view) {
		status = 1;
		statusChanage();
		if (CollectionUtils.isEmpty(wantDramas)) {
			DataDrama.getWantDramas(getContext(), wantLastIndex, getDBCallBack());
		}
	}

	@ClickMethod(R.id.drama_bt_seen)
	protected void clickSeen(View view) {
		status = 2;
		statusChanage();
		if (CollectionUtils.isEmpty(seenDramas)) {
			DataDrama.getSeenDramas(getContext(), seenLashIndex, getDBCallBack());
		}
	}

	private void statusChanage() {
		for (int i = 0; i < topButtons.size(); i++) {
			Button button = topButtons.get(i);
			ListView listView = listViews.get(i);
			if (i == status) {
				button.setBackgroundResource(R.drawable.bg_tab_select);
				viewShow(listView);
			} else {
				button.setBackgroundResource(R.drawable.bg_tab_unselect);
				viewGone(listView);
			}
		}
	}

	class DramaAdap extends BaseAdap {
		private MoreView moreView;

		public DramaAdap(MoreView moreView) {
			this.moreView = moreView;
		}

		@Override
		public Context getContext() {
			return getApplicationContext();
		}

		@Override
		public int getCount() {
			return followDramas == null ? 1 : (followDramas.size() + 1);
		}

		@Override
		public Object getItem(int position) {
			return (position == (getCount() - 1)) ? null : followDramas.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (position == getCount() - 1) {
				return moreView.moreView();
			}

			if (convertView == null || convertView.findViewById(R.id.movie_item_tv_name) == null) {
				convertView = inflate(R.layout.movie_item);
			}

			Drama drama = followDramas.get(position);

			// name
			TextView nameTv = findTextViewById(R.id.movie_item_tv_name, convertView);
			setText(nameTv, drama.getName());

			boolean[] episodes = drama.getEpisodes();

			int startIndex = episodes.length - 1;
			int nextInedx = 0;

			for (int i = startIndex; i >= 0; i--) {
				boolean seen = episodes[i];
				nextInedx = i + 1;
				if (seen && nextInedx < episodes.length && !episodes[nextInedx]) {
					nextInedx++;
					break;
				}

			}

			// date
			TextView dateTv = findTextViewById(R.id.movie_item_tv_date, convertView);
			setText(dateTv, "下一集:第" + nextInedx + "集 总共:" + drama.getTotalNum() + "集");

			return convertView;

		}
	}

	class DramaWantAdap extends BaseAdap {
		private MoreView moreView;

		public DramaWantAdap(MoreView moreView) {
			this.moreView = moreView;
		}

		@Override
		public Context getContext() {
			return getApplicationContext();
		}

		@Override
		public int getCount() {
			return wantDramas == null ? 1 : (wantDramas.size() + 1);
		}

		@Override
		public Object getItem(int position) {
			return (position == (getCount() - 1)) ? null : wantDramas.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == getCount() - 1) {
				return moreView.moreView();
			}

			if (convertView == null || convertView.findViewById(R.id.movie_item_tv_name) == null) {
				convertView = inflate(R.layout.movie_item);
			}

			Drama drama = wantDramas.get(position);

			// name
			TextView nameTv = findTextViewById(R.id.movie_item_tv_name, convertView);
			setText(nameTv, drama.getName());

			// date
			TextView dateTv = findTextViewById(R.id.movie_item_tv_date, convertView);
			String format = DateUtils1.format("yyyyMMdd", "yyyy-MM-dd", drama.getDate());
			setText(dateTv, "上映日期:" + format);

			return convertView;
		}

	}

	class DramaSeenAdap extends BaseAdap {
		private MoreView moreView;

		public DramaSeenAdap(MoreView moreView) {
			this.moreView = moreView;
		}

		@Override
		public Context getContext() {
			return getApplicationContext();
		}

		@Override
		public int getCount() {
			return seenDramas == null ? 1 : (seenDramas.size() + 1);
		}

		@Override
		public Object getItem(int position) {
			return (position == (getCount() - 1)) ? null : seenDramas.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == getCount() - 1) {
				return moreView.moreView();
			}

			if (convertView == null || convertView.findViewById(R.id.movie_item_tv_name) == null) {
				convertView = inflate(R.layout.movie_item);
			}

			Drama drama = seenDramas.get(position);

			// name
			TextView nameTv = findTextViewById(R.id.movie_item_tv_name, convertView);
			setText(nameTv, drama.getName());

			// date
			TextView dateTv = findTextViewById(R.id.movie_item_tv_date, convertView);
			String format = DateUtils1.format("yyyyMMdd", "yyyy-MM-dd", drama.getDate());
			setText(dateTv, "上映日期:" + format);

			return convertView;
		}

	}

	@ClickMethod(R.id.drama_ll_add)
	protected void clickAdd(View view) {
		openActForResult(ActAddDrama.class, RequestCode.ADD_DRAMA);
		animTranslateBottomIn();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == resultOk()) {
			switch (RequestCode.values()[requestCode]) {
			case ADD_DRAMA:
				addDramaBack(data);
				break;
			case WANT_DRAMA_INFO:
				wantInfoBack(data);
				break;
			case FOLLOW_DRAMA_INFO:
				followInfoBack(data);
				break;
			case SEEN_DRAMA_INFO:
				seenInfoBack(data);
				break;
			}
		}
	}

	private void seenInfoBack(Intent data) {
		if (data != null) {
			Drama drama = (Drama) data.getSerializableExtra(Strings.INTENT_EXTRA_DRAMA);
			log("seenInfoBack Drama:" + drama);

			if (drama.getStatus() == 2) {
				oprateSeenDrama.setName(drama.getName());
				oprateSeenDrama.setDate(drama.getDate());
				oprateSeenDrama.setTotalNum(drama.getTotalNum());
				oprateSeenDrama.setSeenNum(drama.getSeenNum());
				oprateSeenDrama.setEpisodes(drama.getEpisodes());
				oprateSeenDrama.setWatchTime(drama.getWatchTime());
			} else if (drama.getStatus() == 0) {
				if (seenDramas != null) {
					seenDramas.remove(oprateSeenDrama);
				}

				if (followDramas != null) {
					followDramas.add(0, drama);
				}

				followAdap.notifyDataSetChanged();
			}

		} else {
			if (seenDramas != null) {
				seenDramas.remove(oprateSeenDrama);
			}
		}
		seenAdap.notifyDataSetChanged();
	}

	private void followInfoBack(Intent data) {

		if (data != null && followDramas != null) {
			Drama drama = (Drama) data.getSerializableExtra(Strings.INTENT_EXTRA_DRAMA);
			if (drama != null && oprateFollowDrama.getWatchTime() != drama.getWatchTime()) {
				followDramas.remove(oprateFollowDrama);
				if (drama.isSeen()) {
					if (seenDramas != null) {
						seenDramas.add(0, drama);
					}
					seenAdap.notifyDataSetChanged();
				} else {
					followDramas.add(0, drama);
				}
			}
		} else {
			followDramas.remove(oprateFollowDrama);
		}

		followAdap.notifyDataSetChanged();
	}

	private void addDramaBack(Intent data) {
		Drama drama = (Drama) data.getSerializableExtra(Strings.INTENT_EXTRA_DRAMA);
		if (wantDramas == null) {
			wantDramas = new ArrayList<Drama>();
		}
		wantDramas.add(0, drama);
		wantAdap.notifyDataSetChanged();
	}

	private void wantInfoBack(Intent data) {

		if (data != null) {
			Drama drama = (Drama) data.getSerializableExtra(Strings.INTENT_EXTRA_DRAMA);

			if (drama.getStatus() == 1) {
				oprateWantDrama.setName(drama.getName());
				oprateWantDrama.setDate(drama.getDate());
				oprateWantDrama.setTotalNum(drama.getTotalNum());
				oprateWantDrama.setEpisodes(drama.getEpisodes());
				oprateWantDrama.setWatchTime(drama.getWatchTime());
				oprateWantDrama.setSeenNum(drama.getSeenNum());

			} else if (drama.getStatus() == 2) {
				if (wantDramas != null) {
					wantDramas.remove(oprateWantDrama);
				}

				if (seenDramas != null) {
					seenDramas.add(0, drama);
				}

				seenAdap.notifyDataSetChanged();
			} else if (drama.getStatus() == 0) {
				if (wantDramas != null) {
					wantDramas.remove(oprateWantDrama);
				}

				if (followDramas != null) {
					followDramas.add(0, drama);
				}

				followAdap.notifyDataSetChanged();
			}

		} else {
			if (wantDramas != null) {
				wantDramas.remove(oprateWantDrama);
			}
		}
		wantAdap.notifyDataSetChanged();

		// if (wantDramas != null) {
		// wantDramas.remove(oprateWantDrama);
		// }
		// wantAdap.notifyDataSetChanged();
		//
		// if (data != null) {
		// Drama drama = (Drama)
		// data.getSerializableExtra(Strings.INTENT_EXTRA_DRAMA);
		// // oprateWantDrama.setEpisodes(drama.getEpisodes());
		// // oprateWantDrama.setStatus(drama.getStatus());
		// // oprateWantDrama.setWatchTime(drama.getWatchTime());
		//
		// if (followDramas != null) {
		// followDramas.add(0, drama);
		// }
		// followAdap.notifyDataSetChanged();
		// }
	}
}
